//
//  AssetsManager.swift
//  Media
//
//  Created by han on 2021/6/8.
//

import UIKit
import Photos



class AssetsManager: NSObject {
    static let shared = AssetsManager()
    
    private override init() {
        super.init()
    }
    
    lazy var cachingImageManager: PHCachingImageManager = {
        let caching = PHCachingImageManager()
        return caching
    }()
    
}

extension AssetsManager {
    func fetchAllAlbums(_ contentType: AlbumContentType, _ showEmptyAlbum: Bool = false, _ showSmartAlbum: Bool = true) -> [AssetsGroup] {
        let allAlbums = PHPhotoLibrary.fetchAllAlbums(contentType, showEmptyAlbum, showSmartAlbum)
        let fetchOptions = PHPhotoLibrary.createFetchOptions(contentType)
        return allAlbums.map { AssetsGroup(assetCollection: $0, fetchAssetsOptions: fetchOptions)}
    }
    
    func saveImage(cgImage: CGImage, assetGroup: AssetsGroup, orientation: UIImage.Orientation, completionBlock: ((AssetItem?, Error?) -> Void)? = nil) {
        PHPhotoLibrary.shared().addImageToAlbum(cgImage: cgImage, orientation: orientation, albumAssetCollection: assetGroup.assetCollection) { success, error, date in
            if success {
                let fetchOptions = PHFetchOptions()
                fetchOptions.predicate = NSPredicate(format: "creationDate = %@", date as NSDate);
                let fetchAssets = PHAsset.fetchAssets(in: assetGroup.assetCollection, options: fetchOptions)
                
                if let asset = fetchAssets.lastObject {
                    let assetItem = AssetItem(asset)
                    completionBlock?(assetItem, error)
                } else {
                    completionBlock?(nil, error)
                }
            } else {
                completionBlock?(nil, error)
            }
        }
    }
}


extension AssetsManager {
    /// 权限：判断是否有权限
    static func isAuthorized(completion: ((Bool) -> Void)? = nil) -> Bool? {
        let status = PHPhotoLibrary.authorizationStatus()
        var authorized: Bool? = false
        switch status {
        case .authorized: // 授权
            authorized = true
        case .notDetermined: // 尚未决定
            authorized = nil
            PHPhotoLibrary.requestAuthorization { (state) in
                DispatchQueue.main.async {
                    if state == .authorized || state == .limited {
                        completion?(true)
                    } else {
                        completion?(false)
                    }
                }
            }
        case .denied: // 拒绝
            authorized = false
        case .restricted: // 没有访问权限
            authorized = false
        case .limited: //  iOS 14  允许访问部分相册内容
            authorized = true
        @unknown default:
            break
        }
        return authorized
    }
}
